package com.hangxin.system.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

public class WordImageUploader extends HttpServlet
{

  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, FileUploadException
  {
	  String path = request.getContextPath();
	  String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";
		
	  boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
	  String url = getServletContext().getRealPath("/upload");
	  String saveUrl  = request.getContextPath() + "/upload/";
	  if (isMultipart) {  
	      // 创建磁盘工厂，利用构造器实现内存数据储存量和临时储存路径  
	       DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 100, new File(url));  
	       PrintWriter out = null;
			try {
				out = response.getWriter();
			} catch (IOException e) {
				e.printStackTrace();
			}
	       ServletFileUpload upload = new ServletFileUpload(factory);  
	       // 设置路径、文件名的字符集  
	      upload.setHeaderEncoding("UTF-8");  
	      // 设置允许用户上传文件大小,单位:字节  
	      upload.setSizeMax(1024 * 1024 * 100);  
	      // 解析请求，开始读取数据  
	      // Iterator<FileItem> iter = (Iterator<FileItem>) upload.getItemIterator(request);  
	      // 得到所有的表单域，它们目前都被当作FileItem  
	       List<FileItem> fileItems = upload.parseRequest(request);  
	      // 依次处理请求  
	       Iterator<FileItem> iter = fileItems.iterator();  
	       String strurl = "";
	      while (iter.hasNext()) {  
	          FileItem item = (FileItem) iter.next();  
	          if (item.isFormField()) {  
	             // 如果item是正常的表单域  
	             String name = item.getFieldName();  
	              String value = item.getString("UTF-8");  
	             // System.out.println("表单域名为:"+name+"表单域值为:"+value);  
	          } else {  
	              // 如果item是文件上传表单域  
	              // 获得文件名及路径  
	             String fileName = item.getName();  
	             String newfileName = "";
	              if (fileName != null) {  
	            	 //重命名
	            	Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));  
	  				Long random = (long) (Math.random() * now);  
	  				newfileName = now + "" + random;  
	  				if (fileName.indexOf(".") != -1) {  
	  					newfileName += fileName.substring(item.getName().lastIndexOf(".")); 
	  				}
	                  // 如果文件存在则上传  
	                 File fullFile = new File(newfileName);  
	                  //if (fullFile.exists()) {  
	                	  strurl = url +"/"+ fullFile.getName();
	                      File fileOnServer = new File(url +"\\"+ fullFile.getName());  
	                     try {
							item.write(fileOnServer);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}  
	                  request.setAttribute("imgpath", strurl); 
	                  request.setAttribute("saveUrl",saveUrl );
	                  RequestDispatcher dispatcher = request.getRequestDispatcher("../util/ckeditor/uploader/upload.jsp"); 
	                  dispatcher .forward(request, response);

	              }  
	          }  
	      } 
	      out.flush();
	      out.close();
	  }  
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    try {
		processRequest(request, response);
	} catch (FileUploadException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    try {
		processRequest(request, response);
	} catch (FileUploadException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
  }

  public String getServletInfo()
  {
    return "Short description";
  }
}